// 请求配置
const baseConfig = {
    baseUrl: 'http://192.168.31.134:5001',
    header: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
    timeout: 60000
}

// 请求拦截器
const requestInterceptor = (config) => {
    // 获取token
    const token = uni.getStorageSync('token')
    if (token) {
        config.header['Authorization'] = `Bearer ${token}`
    }
    return config
}

// 响应拦截器
const responseInterceptor = (response) => {
    const { statusCode, data } = response

    // 请求成功
    if (statusCode === 200) {
        return data
    }

    // 处理错误
    let message = '请求失败'
    if (data && data.message) {
        message = data.message
    }

    uni.showToast({
        title: message,
        icon: 'none'
    })

    return Promise.reject(message)
}

// 统一请求方法
const request = (options = {}) => {
    // 合并配置
    const config = {
        ...baseConfig,
        ...options,
        url: baseConfig.baseUrl + (options.url || ''),
        header: {
            ...baseConfig.header,
            ...options.header
        }
    }

    // 请求拦截
    const finalConfig = requestInterceptor(config)

    // 发起请求
    return new Promise((resolve, reject) => {
        uni.request({
            ...finalConfig,
            success: (response) => {
                try {
                    const result = responseInterceptor(response)
                    resolve(result)
                } catch (error) {
                    reject(error)
                }
            },
            fail: (error) => {
                uni.showToast({
                    title: '网络异常',
                    icon: 'none'
                })
                reject(error)
            }
        })
    })
}

// 导出请求方法
export default request